<template>
    <div>
        <a-modal
            :title="versionInfo.id ? '编辑预发布版本' : '新增预发布版本'"
            centered
            v-model:visible="visible"
            :confirm-loading="loading"
            :width="600"
            okText="确认"
            @ok="handleSave"
            @cancel="handleCancel"
        >
            <a-form ref="ruleFormRef" layout="inline" :model="form" :rules="rules">
                <a-row>
                    <a-col :span="24">
                        <a-form-item label="PBI目录" name="catalogCode">
                            <!-- 不统一发版 -->
                            <span v-if="subVersionInfo.signPostShowType === '3' && treeData.length">
                                <SelectCatalogCode
                                    ref="SelectCatalogCodeRef"
                                    v-model:value="form.catalogCode"
                                    :defaultTreeData="treeData"
                                    :levelLimit="3"
                                    :changeOnSelect="true"
                                />
                            </span>
                            <span v-else> {{ pbiName }} </span>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="版本号" :span="24" name="versionNumber" class="version-number-form-item">
                            <div>
                                <VersionNumberInput
                                    ref="versionNumberInputRef"
                                    :versionInfo="versionInfo"
                                    :subVersionInfo="subVersionInfo"
                                    :lubiaoDetail="lubiaoDetail"
                                    v-if="visible"
                                />
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="时间阶段" name="startTime">
                            <h-range-picker-cell
                                :placeholder="['请选择开始时间', '请选择上线时间']"
                                :value="[
                                    form['startTime'] ? $moment(form['startTime'], 'YYYY-MM-DD') : null,
                                    form['onlineTime'] ? $moment(form['onlineTime'], 'YYYY-MM-DD') : null
                                ]"
                                @change="rangeDateChange"
                            />
                        </a-form-item>
                    </a-col>
                    <!-- 统一发版 -->
                    <a-col :span="24" v-if="isUnifyRelease">
                        <a-form-item label="提示">
                            <div class="caption-font-color">
                                <span> 选中的产品将同步创建预发布版本流程</span>
                                <a-tooltip>
                                    <template #title>
                                        <span>仅产品经理有该系统权限时才可创建预发布版本</span>
                                    </template>
                                    <QuestionCircleOutlined class="margin-l-8" />
                                </a-tooltip>
                            </div>
                            <flexbox style="width: 100%">
                                <a-checkbox-group v-model:value="checkedList">
                                    <a-row>
                                        <a-col :span="12" v-for="item of subApplySystemList" :key="item.catalogCode">
                                            <a-checkbox
                                                :disabled="versionInfo.id && oldCatalogCodeCv.indexOf(item.catalogCode) >= 0"
                                                :value="item.catalogCode"
                                            >
                                                {{ item.catalogName }}
                                            </a-checkbox>
                                        </a-col>
                                    </a-row>
                                </a-checkbox-group>
                            </flexbox>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts">
import api from '@/api';
import { SelectCatalogCode } from '@/components';
import VersionNumberInput from './VersionNumberInput.vue';
import { transformDataByFlatProperty } from '@/utils/tree';
import { deepClone } from '@/utils/util';
import { message } from 'ant-design-vue';
import { treeFilter, findNodeById } from '@/utils/tree';
import { HRangePickerCell } from '@/components';
import { QuestionCircleOutlined } from '@ant-design/icons-vue';
import { defineComponent, ref, unref, reactive, toRefs, onDeactivated, computed, nextTick } from 'vue';
export default defineComponent({
    components: {
        VersionNumberInput,
        HRangePickerCell,
        SelectCatalogCode,
        QuestionCircleOutlined
    },
    props: {
        lubiaoDetail: {
            type: Object,
            default: () => ({})
        },
        subVersionInfo: {
            type: Object,
            default: () => ({})
        }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const ruleFormRef = ref<any>();
        const SelectCatalogCodeRef = ref<any>();
        const versionNumberInputRef = ref<any>();
        const state = reactive<any>({
            form: {
                versionNumber: '',
                startTime: '',
                onlineTime: '',
                catalogCode: ''
            },
            visible: false,
            loading: false,
            pbiName: '',
            versionInfo: {},
            treeData: [],
            subApplySystemList: [],
            checkedList: [],
            oldCatalogCodeCv: ''
        });
        // 是否统一发板
        const isUnifyRelease = computed(() => {
            return props.subVersionInfo.signPostShowType === '2';
        });
        const validateVersionNumber = async () => {
            const res = await unref(versionNumberInputRef).validate();
            return !res ? Promise.reject('') : Promise.resolve();
        };
        const validateRangeTime = async () => {
            if (!state.form.onlineTime) {
                return Promise.reject('上线时间不能为空');
            } else {
                return Promise.resolve();
            }
        };
        const rules = {
            versionNumber: [{ validator: validateVersionNumber, trigger: 'change' }],
            startTime: [
                { required: true, message: '开始时间不能为空', trigger: 'change' },
                { validator: validateRangeTime, trigger: 'change' }
            ]
        };
        const open = (versionInfo) => {
            console.log(versionInfo);
            state.versionInfo = versionInfo || {
                type: '3'
            };
            init();
            state.visible = true;
        };
        const init = () => {
            nextTick(() => {
                unref(ruleFormRef) && unref(ruleFormRef).clearValidate();
            });
            if (state.versionInfo.id) {
                state.form.startTime = state.versionInfo.startTime;
                state.form.onlineTime = state.versionInfo.onlineTime;
                state.form.catalogCode = state.versionInfo.catalogCode;
                if (state.versionInfo.catalogCodeCv) {
                    state.checkedList = state.versionInfo.catalogCodeCv.split(',');
                    state.oldCatalogCodeCv = state.versionInfo.catalogCodeCv.split(',');
                }
            } else {
                resetForm();
            }
            if (unref(isUnifyRelease)) {
                getSubPro();
            }
            getPbiTreeData();
        };
        const resetForm = () => {
            state.form = {
                versionNumber: '',
                startTime: '',
                onlineTime: '',
                catalogCode: props.lubiaoDetail.catalogCode
            };
            state.checkedList = [];
        };
        const handleSelectChange = (val) => {
            state.list = [...val];
        };
        // 保存版本号
        const handleSave = async () => {
            unref(ruleFormRef)
                .validate()
                .then(async () => {
                    state.form.versionNumber = unref(versionNumberInputRef).versionNumber;
                    const query = {
                        ...state.versionInfo,
                        id: state.versionInfo.id || null,
                        ...state.form,
                        randdStartTime: state.form.startTime,
                        type: '3',
                        parentId: props.subVersionInfo.id
                    };
                    // 统一发版本
                    if (unref(isUnifyRelease)) {
                        // 是否有旧的子产品记录
                        if (state.oldCatalogCodeCv) {
                            const arr: any = [];
                            state.checkedList.forEach((item) => {
                                if (state.oldCatalogCodeCv.indexOf(item) < 0) {
                                    arr.push(item);
                                }
                            });
                            if (arr.length) {
                                query.catalogCodeCv = arr.join(',');
                            } else {
                                query.catalogCodeCv = null;
                            }
                        } else {
                            query.catalogCodeCv = state.checkedList.length ? state.checkedList.join(',') : '';
                        }
                    } else {
                        query.catalogCodeCv = state.form.catalogCode;
                    }
                    const { success, errorMsg } = await api.versionControlModel.save(query);
                    if (success) {
                        message.success(state.versionInfo.id ? '编辑成功' : '新增成功');
                        emit('success');
                        state.visible = false;
                    } else {
                        message.error(errorMsg);
                    }
                });
        };
        // 获取所有pbi数据
        const getPbiTreeData = async () => {
            const query = {
                type: 2
            };
            const { success, moule } = await api.portalControlModel.getSystemProductCatalogTreeData(query);
            if (success) {
                if (moule) {
                    state.pbiTreeData = transformDataByFlatProperty(deepClone(JSON.parse(moule)));
                    const treePathArr = treeFilter(state.pbiTreeData, (node) => node.catalogCode === props.lubiaoDetail.catalogCode);
                    const target = findNodeById(
                        {
                            subNodes: state.pbiTreeData,
                            catalogCode: ''
                        },
                        props.lubiaoDetail.catalogCode
                    );
                    if (target) {
                        state.treeData = [target];
                    }
                    state.pbiName = getPbiName(treePathArr, '');
                }
            }
        };
        const getPbiName = (target, name) => {
            if (target && target.length) {
                if (name) {
                    name = `${name} / ${target[0].catalogName}`;
                } else {
                    name = target[0].catalogName;
                }
                return getPbiName(target[0].subNodes, name);
            }
            return name;
        };
        const handleCancel = () => {
            state.visible = false;
        };
        // 日期
        const rangeDateChange = (val) => {
            const { startTime, endTime } = val;
            state.form.startTime = startTime;
            state.form.onlineTime = endTime;
        };
        // 获取系统
        const getSubPro = async () => {
            const query = {
                catalogCode: props.subVersionInfo.catalogCode
            };
            const { success, moule } = await api.versionControlModel.getUserSubProductCatalogs(query);
            if (success) {
                state.subApplySystemList = [...moule];
            }
        };
        // 销毁时关闭弹窗
        onDeactivated(() => {
            state.visible = false;
        });
        return {
            ruleFormRef,
            versionNumberInputRef,
            SelectCatalogCodeRef,
            ...toRefs(state),
            rules,
            isUnifyRelease,
            open,
            handleSelectChange,
            handleSave,
            handleCancel,
            rangeDateChange
        };
    }
});
</script>

<style scoped lang="less">
::v-deep(.version-number-form-item) {
    .ant-form-item-explain-error {
        display: none;
    }
}
::v-deep(.ant-form-inline .ant-form-item-label) {
    min-width: 160px !important;
}
::v-deep(.ant-checkbox-group) {
    width: 100% !important;
}
</style>